<template>
	<div class="content" id="scrollDiv">
		<p class="head_tips">在这可以直接私信互动了～</p>
		<div class="list" v-for="(item,index) in dataList" :key="index">
			<div class="time">{{item.createDate}}</div>

			<div class="left" v-if="userId != item.fromUserId">
				<img :src="item.avatar?item.avatar:'/static/mr_tx.png'" alt="">
				<p v-if="!item.img" class="text" selectable>{{item.message}}</p>
				<p v-else class="text" selectable>
					<img @click="previewImg(item.img)" :src="item.img" alt="">
				</p>
			</div>
			<div class="right" v-else>
				<p v-if="!item.img" class="text" selectable>{{item.message}}</p>
				<p v-else class="text" selectable>
					<img @click="previewImg(item.img)" :src="item.img" alt="">
				</p>
				<img :src="item.avatar?item.avatar:'/static/mr_tx.png'" alt="">
			</div>
		</div>
		
		<div class="input_box">
			<div class="box">
				<div class="label">
					<p @click="toLocal"><img src="/static/s_icon1.png" alt="">本地一手</p>
					<p @click="makePhoneCall"><img src="/static/s_icon2.png" alt="">联系方式</p>
					<p v-if="!userMsg.state" @click="clickPb"><img src="/static/s_icon3.png" alt="">屏蔽私信</p>
					<p class="on" v-else @click="clickPb"><img src="/static/s_icon3_on.png" alt="">已屏蔽</p>
					<p @click="toExposure"><img src="/static/bg_user.png" alt="">曝光他</p>
				</div>
				<div class="sr_input" ref="container">
					<u--textarea 
					:adjustPosition="false" 
					v-model="input_value" 
					cursorSpacing="300" 
					:showConfirmBar="false"
					height="19px" 
					@focus="changeFocus"
					@blur="changeBlur"
					placeholder="请输入内容" 
					autoHeight 
					></u--textarea>
					<p @click="sendOut">发送</p>
					<img v-if="!upHeight" @click="addUpImg" src="/static/plus-add.png" alt="">
					<img v-else @click="hideUpImg" src="/static/plus-add.png" alt="">
				</div>
				<div @click="changeImg" class="up_img" :style="{height:upHeight+'rpx'}">
					<p class="img">
						<img src="/static/up_img.png" alt="">
					</p>
					<p class="text">图片</p>
				</div>
				<div :style="{ height: keyboardHeight + 'px' }"></div>
			</div>
		</div>
	</div>
</template>

<script>
	import { mapState ,mapActions} from 'vuex'
	import api from '@/api';
	import WebsocketTask from './websocket.js';
	import Config from '@/config/index.js'
	import { formatTimestamp } from '@/utils/utils.js'
	export default {
		data() {
			return {
				input_value:'',
				dataList:[],
				keyboardHeight: 0,
				websocket:null,
				newId:'',
				bAvatar:'',
				param:{
					memberUserId:'',
					sendUserId:'',
					pageNo:0,
					pageSize:10
				},
				setData:{},
				upHeight:0,
				keyboardHeight: 0,
				userMsg:{}
			}
		},
		computed: {
			...mapState({
				userTx:state => state.user.userTx,
				baseurl: state => state.user.baseurl,
				token:state => state.user.token,
				userId:state => state.user.userId,
				userName:state => state.user.userName,
			})
		},
		onLoad(options) {
			console.log(options.setData)
			this.setData = JSON.parse(options.setData)
			this.param.memberUserId = this.setData.memberUserId
			this.param.sendUserId = this.userId
			uni.setNavigationBarTitle({
				title: this.setData.memberUserName
			});
			this.getList()

			this.getUserState()
		},
		onUnload() {
			uni.closeSocket({
				success: () => {
					console.log('WebSocket连接已关闭');
				}
			});
		},
		onShow(){
			
			
			// let websocket = new WebsocketTask(`ws://192.168.0.104:48080/infra/ws?token=${this.token}`);

			// 发送消息
			uni.connectSocket({
				url: `${Config.apiSocket}${this.token}`, // WebSocket服务器地址
				header:{
					'content-type': 'application/json'
				},

			});

			// 连接打开
			uni.onSocketOpen(function (res) {
				console.log('WebSocket连接已打开');
			});

			// 接收消息
			uni.onSocketMessage((res) => {
				console.log('收到WebSocket服务器消息：', res.data);
				
				const jsonMessage = JSON.parse(res.data)
				const type = jsonMessage.type
				const content = JSON.parse(jsonMessage.content)
				const {avatar,message,nickName,pictureList,createDate} = JSON.parse(content.text)
				console.log(type)
				console.log(content)
				if(pictureList && pictureList.length){
					this.dataList.push({
						avatar,
						img:pictureList[0],
						fromUserId:content.fromUserId,
						createDate:formatTimestamp(createDate)
					})
				}else{
					this.dataList.push({
						avatar,
						message,
						fromUserId:content.fromUserId,
						createDate:formatTimestamp(createDate)
					})
				}
				
				if (!type) {
					return
				}
			});
		},
		methods: {

			getUserState(){
				let data = {
					userId:this.userId,
					screenUserId:this.param.memberUserId,
				}
				api.user.user_chat(data).then(res=>{
					if(res.code == 200){
						this.userMsg = res.data
					}
				})
			},

			clickPb(){
				let state = this.userMsg.state
				uni.showModal({
				title: '提示',
				content: state?'是否取消屏蔽此用户':'是否屏蔽此用户',
				showCancel: true,
				cancelText: '取消',
				confirmText: '确定',
					success:(res)=>{
						if (res.confirm) {
							let data = {
								userId:this.userId,
								screenUserId:this.param.memberUserId,
								state:state?0:1
							}
							api.user.update_screen(data).then(res=>{
								if(res.code == 200){
									this.getUserState()
								}
							})
						} 
					},
				});
			},

			makePhoneCall() {
				uni.makePhoneCall({
					phoneNumber: this.userMsg.mobile, // 替换为实际电话号码
					success: () => {
					console.log('拨打电话成功');
					},
					fail: (err) => {
					console.error('拨打电话失败', err);
					}
				});
			},

			changeFocus(){
				this.keyboardHeight = 300
			},
			changeBlur(){
				this.keyboardHeight = 0
			},

			// 跳转曝光
			toExposure(){
				console.log(this.param.memberUserId)
				uni.navigateTo({
					url: `/pages/exposure/index?bgName=${this.setData.memberUserName}&memberId=${this.param.memberUserId}`
				});
			},

			previewImg(imgurl) {
				uni.previewImage({
				current: imgurl, // 当前显示图片的http链接
				urls: [imgurl] // 需要预览的图片http链接列表
				});
			},

			changeImg(){
				uni.chooseImage({
					count: 1, // 默认最多可以选择的图片张数
					sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
					success:(item)=>{
						console.log('aaaa')
						console.log(item)
						uni.showModal({
							title: '提示',
							content: '确定发送该图片',
							showCancel: true,
							cancelText: '取消',
							confirmText: '确定',
								success:(res)=>{
									if (res.confirm) {
										uni.showLoading({title: '发送中...'})
										uni.uploadFile({
											url: `${Config.apiUpload}`,
											name: 'file',
											method: 'POST',
											filePath: item.tempFilePaths[0],
											header: {
												'Authorization': `Bearer ${this.token}`,
											},
											formData: {
												file: item.tempFilePaths[0],
											},
											success: (res) => {
												let returnData = JSON.parse(res.data)
												console.log(returnData)
												this.input_value = ''
												this.setMsgSubmit(false,returnData.data)
											},
											fail: (err) => {
												uni.hideLoading()
												this.$toast('发送失败，请重新上传！')
											}
										})
									} 
								},
							});
					}
				});
			},

			addUpImg(){
				this.upHeight = 150
			},

			hideUpImg(){
				this.upHeight = 0
			},

			toLocal(){
				uni.navigateTo({
					url: '/pages/local/index'
				});
			},

			// 获取消息
			getList(){
				api.user.chat_list(this.param).then(res=>{
					if(res.code == 200){
						res.data.list.map(item=>{
							if(item.pictureList && item.pictureList.length){
								this.dataList.push({
									avatar:item.avatar,
									img:item.pictureList[0],
									fromUserId:item.sendUserId,
									createDate:formatTimestamp(item.createDate)
								})
							}else{
								this.dataList.push({
									avatar:item.avatar,
									message:item.message,
									fromUserId:item.sendUserId,
									createDate:formatTimestamp(item.createDate)
								})
							}
							
						})
					}
				})
			},



			setMsgSubmit(state,img){
				uni.hideLoading()
				let messageContent = {}
				let state_s = 0
				// 都没屏蔽
				if(!this.userMsg.coverState && this.userMsg.state){
					state_s = 0
				}
				if(!this.userMsg.coverState && this.userMsg.state){
					state_s = 1 // 我屏蔽
				}
				if(this.userMsg.coverState && !this.userMsg.state){
					state_s = 2 // 对方屏蔽
				}
				if(this.userMsg.coverState && this.userMsg.state){
					state_s = 3 // 双方屏蔽
				}
				if(state){// 发送文字
					messageContent = JSON.stringify({
						toUserId:this.param.memberUserId,
						text:JSON.stringify({
							message:this.input_value,
							state:state_s,
						})
					})
				}else{// 发送图片
					messageContent = JSON.stringify({
						toUserId:this.param.memberUserId,
						text:JSON.stringify({
							pictureList:[img],
							state:state_s,
						})
					})
				}
				console.log(messageContent)

				// JSON 化整个消息
				let jsonMessage = JSON.stringify({
					type: "chat-message-send",
					content:messageContent
				})
		
				uni.sendSocketMessage({
					data: jsonMessage
				});

				// 第一次创建私聊
				if(!this.dataList.length){
					let data = {
						newId:this.setData.id,
						// message:this.input_value,
						memberUserId:this.userId,
						chatUserId:this.param.memberUserId,
						avatar:this.setData.bAvatar,
						memberUserName:this.setData.memberUserName,
						chatUserName:this.userName
					}
					console.log(data)
					api.user.message_create(data).then(res=>{
						
					})
				}

				if(state){// 发送文字
					this.dataList.push({
						avatar:this.userTx,
						message:this.input_value,
						fromUserId:this.userId,
						createDate:formatTimestamp(Date.now())
					})
				}else{
					this.dataList.push({
						avatar:this.userTx,
						img,
						fromUserId:this.userId,
						createDate:formatTimestamp(Date.now())
					})
				}
				
				this.input_value = ''
				this.scrollToBottom()
			},

			// 发送信息
			sendOut(){
				if(!this.input_value){
					return
				}
				this.setMsgSubmit(true)
			},

			// 内容到底向上移动
			scrollToBottom() {
				const query = uni.createSelectorQuery();
				query.select('#scrollDiv').boundingClientRect((rect) => {
					if (rect) {
						uni.pageScrollTo({
							scrollTop: rect.height,
							duration: 200
						});
					}
				});
				query.exec();
			},
		},
	}
</script>

<style lang="scss" scoped>
	$tx_height:92rpx;
	$tx_margin:18rpx;
	$input_an_height:80rpx;
	.content{
		min-height: 100vh;
		background: #FAFAFA;
		padding:0 26rpx;
		.head_tips{
			text-align: center;
			color:#999999;
			font-size:26rpx;
			padding:30rpx 0 20rpx 0;
		}
		.list{
			&:first-child{
				.time{
					padding-top:30rpx;
				}
			}
			.time{
				text-align: center;
				padding-bottom:30rpx;
				font-size:24rpx;
				color:#999999;
			}
			.left{
				width: 100%;
				display: flex;
				margin-bottom:40rpx;
				img{
					width: $tx_height;
					height: $tx_height;
					border-radius: 8rpx;
				}
				.text{
					max-width: 80%;
					background: #fff;
					margin:0 0 0 $tx_margin;
					font-size:30rpx;
					color:#333;
					padding:24rpx;
					border-radius: 0 20rpx 20rpx 20rpx;
					word-wrap: break-word;
  					overflow-wrap: break-word;
					img{
						width: 300rpx;
						height: 300rpx
					}
				}
			}
			.right{
				@extend .left;
    			justify-content: flex-end;
				.text{
					background: #23AC39;
					color:#fff;
					margin:0 $tx_margin 0 0;
					border-radius: 20rpx 0rpx 20rpx 20rpx;
				}
			}
		}
		.input_box{
			width: 100%;
			min-height: 220rpx;
			.box{
				width: 94%;
				position: fixed;
				bottom:0;
				left: 0;
				padding:24rpx;
				padding-top:0;
				z-index: 10;
				background: #F1F1F1;
				box-shadow: 0px 8rpx 20rpx 0px rgba(0, 0, 0, 0.5);
				.label{
					margin-bottom:20rpx;
					display: flex;
					flex-wrap:wrap;
					p{
						display: flex;
						align-items: center;
						padding:12rpx 16rpx;
						background: #fff;
						border-radius: 10rpx;
						margin-right:14rpx;
						color: #23AC39;
						font-size:24rpx;
						margin-top:24rpx;
						&:last-child{
							margin-right:0;
						}
						img{
							width: 30rpx;
							height: 30rpx;
							margin-right:10rpx;
						}
						&.on{
							color:#FF4441;
						}
					}
				}
				.sr_input{
					display: flex;
					align-items: center;
					justify-content:  space-between;
					/deep/ .u-textarea{
						width: 66%;
						background: #fff;
						padding:24rpx;
						border-radius: 10rpx;
						font-size:28rpx;
						flex: inherit;
						border:none;
						-webkit-appearance: none;
						color: #000;
					}
					p{
						width: 108rpx;
						height: $input_an_height;
						line-height: $input_an_height;
						background: #23AC39;
						border-radius: 10rpx;
						font-size:28rpx;
						color:#fff;
						text-align: center;
					}
					img{
						width: 48rpx;
						height: 48rpx;
					}
				}
				.up_img{
					height: 0;
					transition: all 0.3s;
					width: 150rpx;
					overflow: hidden;
					.img{
						width: 80rpx;
						height: 80rpx;
						background: #fff;
						border-radius: 10rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						margin:30rpx 0 0 30rpx;
						img{
							width: 50rpx;
							height: 50rpx;
						}
					}
					.text{
						width: 80rpx;
						margin-left:30rpx;
						text-align: center;
						font-size:22rpx;
						margin-top:10rpx;
						color:#999;
					}
				}
			}
		}
	}
</style>
